const app = getApp()
const WXAPI = require('../../wxapi/main')
// var tool = require('../../utils/utils.js');
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 选项卡
    tabs: ["需求市场", "已完成需求"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,

    TabCur: 0,
    scrollLeft:0,
    
    reqTitle: '',
    reqStatus: '',
    petGoodsList: [], //放置返回数据的数组  
    isFromSearch: true, // 用于判断petGoodsList数组是不是空数组，默认true，空的数组
    searchPageNum: 1, // 设置加载的第几次，默认是第一次
    callbackcount: 10, //返回数据的个数
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏  
    searchLoadingComplete: false, //“没有数据”的变量，默认false，隐藏 

    isNetWork: false,
    partUserInfo: null
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id-1)*60
    })
  },
  tabClick: function(e) {
    console.log('exec tab click')
    var _activeIndex = e.currentTarget.id
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: _activeIndex,
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id-1)*60
    });
    var _reqStatus = 'published'
    if (e.currentTarget.id === '1') {
      _reqStatus = 'completed'
    }
    this.setData({
      reqStatus: _reqStatus,
      searchPageNum: 1, //第一次加载，设置1  
      petGoodsList: [], //放置返回数据的数组,设为空  
      isFromSearch: true, //第一次加载，设置true  
      searchLoading: true, //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete: false //把“没有数据”设为false，隐藏  
    })
    this.loadGoods()
  },

  goReqDetail: function(e) {
    console.log(' e ', e)
    let that = this
    let reqId = e.currentTarget.dataset.reqId;   
    if (!that.data.partUserInfo) {
      wx.navigateTo({
        url: "/pages/req/detail?reqId=" + reqId
      })
    } else {
      let currentOpenId = that.data.partUserInfo?.openid
      let openId = e.currentTarget.dataset.openId
      console.log('currentOpenId ', currentOpenId)
      console.log('openId ', openId)
      if (openId === currentOpenId) {
        console.log('要跳转倒我发布的明细界面')      
        wx.navigateTo({
          url: '/pages/req-detail/index?reqId=' + reqId,
        })
        return
      } else {
        wx.navigateTo({
          url: "/pages/req/detail?reqId=" + reqId
        })
      }      
    }
  },
  

  loadGoods: function() {
    var that = this
    var postData = {
      reqTitle: that.data.reqTitle,
      reqStatus: that.data.reqStatus,
      searchPageNum: that.data.searchPageNum,
      callbackcount: that.data.callbackcount,
    };
    // console.log('require....... ', postData)
    WXAPI.loadReqList(postData)
      .then(function(res) {
        if (res.code == 0) {
          let retData = res.data
          console.log('ret data is ', retData)
          if (retData.length > 0) {
            let searchList = [];
            //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加  
            that.data.isFromSearch ?
              searchList = retData :
              searchList = that.data.petGoodsList.concat(retData)
            if (retData.length < that.data.callbackcount) {
              that.setData({
                petGoodsList: searchList, //获取数据数组 
                searchLoadingComplete: true, //把“没有数据”设为true，显示  
                searchLoading: false //把"上拉加载"的变量设为false，隐藏  
              })
            } else {
              that.setData({
                petGoodsList: searchList, //获取数据数组 
                searchLoading: false //把"上拉加载"的变量设为false，显示 
              });
            }
            //没有数据了，把“没有数据”显示，把“上拉加载”隐藏          
          } else {
            that.setData({
              searchLoadingComplete: true, //把“没有数据”设为true，显示  
              searchLoading: false //把"上拉加载"的变量设为false，隐藏  
            })
          }
        }
      })
  },

  searchGoods: function(e) {
    console.log('searchGoods', e.detail)
    let that = this
    that.setData({
      reqTitle: e.detail,
      searchPageNum: 1
    }, ()=> {
      console.log('exec on show')
      that.onShow()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('options ', options)
    if (options.inviteCode) {
      // 有人推荐进来的
      wx.setStorageSync('inviteCode', options.inviteCode)
    }
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    that.setData({
      reqStatus: 'published',     
      searchPageNum: 1, //第一次加载，设置1  
      petGoodsList: [], //放置返回数据的数组,设为空  
      isFromSearch: true, //第一次加载，设置true  
      searchLoading: true, //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete: false, //把“没有数据”设为false，隐藏  
    })
    // word count
    let skey = wx.getStorageSync('loginFlag')
    if (skey) {
      WXAPI.countWord({skey: skey}).then(res => {
        console.log('load count word ', res)
        if (res.code === 0) {
          console.log('set bar badge ')
          wx.showTabBarRedDot({
            index: 1,
          })
        }
      })
      // 关系网
      WXAPI.loadNetworkList({skey})
      .then(res => {
        console.log('res ', res)
        if (res.code === 0) {
          let netWorkList = res.data
          if (netWorkList.length >0) {
            that.setData({
              isNetWork: true
            })
          }          
        }
      })
    }
    // currn user
    if (!that.data.partUserInfo) {
      var _partUserInfo = wx.getStorageSync('partUserInfo')
      if (_partUserInfo) {
        that.setData({
          partUserInfo: _partUserInfo
        })
      }
    }   
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    if (!that.data.partUserInfo) {
      var _partUserInfo = wx.getStorageSync('partUserInfo')
      if (_partUserInfo) {
        that.setData({
          partUserInfo: _partUserInfo
        })
      }
    }   

    that.loadGoods();
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function(e) {
    console.log('onPullDownRefresh')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(e) {
    console.log('onReachBottom ...')
    var that = this
    that.setData({
      searchPageNum: that.data.searchPageNum + 1,
      isFromSearch: false,
      searchLoading: true //把"上拉加载"的变量设为false，隐藏  

    })
    that.loadGoods()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this
    if (!that.data.currentMerCode) {
      console.log('分享无效,未知宠物店编号')
      return null
    }
    console.log('ready share ... ', that.data.currentMerCode)
    return {
      title: '宠崽崽', // 转发后 所显示的title
      path: '/pages/index/index?merchantCode=' + that.data.currentMerCode, // 相对的路径
      success: (res) => { // 成功后要做的事情
        console.log('首页分享反馈', res)
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        // console.log(res.shareTickets[0])        
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: (res) => {
            console.log('success', res)
          },
          fail: function(res) {
            console.log('fail', res)
          },
          complete: function(res) {
            console.log('complete ', res)
          }
        })
      },
      fail: function(res) {
        // 分享失败
        console.log(res)
      }
    }
  }
})